/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ContentManagers.Servlets;

//import ContentManagers.RoleManagers.CustomerManager;
import ContentManagers.Models.Customer;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ContentManagers.RoleManagers.CustomerSessionManager;
import ContentManagers.Models.TransactionManager;
import javax.servlet.http.HttpSession;
import ContentManagers.RoleManagers.CustomerManager;
import ContentManagers.RoleManagers.PMManager;
import java.sql.*;
/**
 *
 * @author Martin San Diego
 */
public class ServletPurchaseItems extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
            HttpSession session = request.getSession();
            boolean indb, checker = false;
            
            Customer reAuth = new Customer();
            reAuth.setUsername(session.getAttribute("username").toString());
            reAuth.setPassword(request.getParameter("reAuthPassword"));
            
            checker = new CustomerManager().checkCustomer(reAuth);
            
            if(checker)
            {
                //employ servlet-level authorization here
                    indb = new CustomerSessionManager().checkSession(session.getAttribute("username").toString(), request.getRemoteAddr().toString(), session.getAttribute("sessionID").toString());

                    if(indb == false)
                        response.sendRedirect("index.jsp");
                    else
                    {   boolean result = false;
                        //this section would require an AUTO-COMMIT OFF setting because two queries will be executed
                        try {
                                int customer_id = CustomerManager.getCustomerID(session.getAttribute("username").toString());

                                if(customer_id != -111) //invalid username in session variable
                                {   
                                    result = new TransactionManager().newTransaction(customer_id);

                                    if(result == true) //get transactionID of last the successful transaction
                                    {
                                        int latestTransID = new TransactionManager().getLastTransactionID(Integer.toString(customer_id));

                                        if(latestTransID != -111) //no record found in DB
                                        {

                                            result = addItemsInCart(latestTransID, request, session);

                                        }

                                    }

                                }

                                if(result == true)
                                {
                                    session.removeAttribute("cartArray");
                                    response.sendRedirect("user_purchases.jsp");
                                }
                            }catch(Exception e){e.printStackTrace();}
                    }
            }
            
            else 
            { 
                session.setAttribute("errorMessage", "falseAuth");
                response.sendRedirect("user_cart.jsp");
            }
            
            
            
        } finally {            
            out.close();
        }
    }
    
    public static boolean addItemsInCart(int transaction_id, HttpServletRequest request, HttpSession session)
    {   boolean result = false;
        try{
            int cartDepth = 0;
        
            int cartHeight, test = 0;
            ResultSet rs;
            Object cartObject = session.getAttribute("cartArray");
            String[][] userCart = (String[][])cartObject;
            cartHeight = userCart[0].length;

            for(test = 0; test < cartHeight; test++) //get cartDepth
                if(userCart[0][test] != null)
                { 
                    cartDepth++;
                    rs = new PMManager().getProduct(userCart[0][test]); 
                    if(rs == null ||cartDepth == 0)
                        {
                            //give out error message
                        }
                    else
                        {
                        while(rs.next())
                            {
                             result = new TransactionManager().addTransactionItem(Integer.toString(transaction_id), userCart[1][test], rs.getString("product_id"), rs.getString("price"));   
                             //System.out.print(Integer.toString(transaction_id) + "-" + userCart[1][test] + "-" + rs.getString("product_id") + "-" + rs.getString("price"));
                            }
                        }

                }
            
           }catch(Exception e){ //give out error message 
                
           }   
        return result;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
